<template>
  <el-row :gutter="20" style="width: 100%">
    <el-col :span="4"></el-col>
    <el-col :span="16">
      <p>
        <h1>论坛中心</h1>
      </p>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="发表论坛" name="1">
          <el-form :model="publishform">
            <el-form-item label="标题">
              <el-input v-model="publishform.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="内容">
              <el-input v-model="publishform.content" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handlePostsAdd">发表</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <el-timeline style="min-width: 100%;margin-top: 10px;">
        <el-timeline-item v-for="(post, index) in posts" :key="post.id" style="min-width: 100%">
          <div class="user-info-container" style="min-width: 100%">
            <el-avatar size="large" :src="post.avatar"></el-avatar>
            <div class="user-info">
              <div class="user-details">
                <p>
                  {{ post.username }}<span style="margin-left: 5px;">{{ formatTime(post.createdAt) }}</span>
                  <el-button type="text" @click="handleReply(post)" style="margin-left: 5px;">回复</el-button>
                  <el-button type="text" v-if="post.userId===userStore.id" @click="handledelete(post,1)"
                             style="margin-left: 5px;">删除
                  </el-button>
                </p>
              </div>
              <!-- 帖子的主要内容 -->
              <div class="user-content">
                <p>标题:{{ post.title }}</p>
                <p>内容:{{ post.content }}</p>
              </div>
              <!-- 子节点内容的垂直排列 -->
              <div class="replies-container">
                <div v-for="(child, childIndex) in post.children" :key="child.id" style="margin-top: 5px">
                  <el-card>
                    <div class="user-details">
                      <el-avatar size="large" :src="child.avatar"></el-avatar>
                      <p>
                        {{ child.username }}<span style="margin-left: 5px;">{{ formatTime(child.createdAt) }}</span>
                        <el-button type="text" v-if="child.userId===userStore.id" @click="handledelete(child,2)"
                                   style="margin-left: 5px;">删除
                        </el-button>
                      </p>
                    </div>
                    <!-- 帖子的主要内容 -->
                    <div class="user-content">
                      <p>@{{ post.username }}的回复：{{ child.content }}</p>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>

      <!-- 分页器 -->
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="findAll"
          @size-change="handler"
      />
    </el-col>
    <el-col :span="4"></el-col>
  </el-row>

  <!-- 回复弹出框 -->
  <el-dialog title="回复" v-model="dialogVisible" width="30%">
    <el-form :model="replyform">
      <el-form-item label="回复内容">
        <el-input v-model="replyform.content" type="textarea" placeholder="请输入内容"></el-input>
        <el-button type="primary" @click="handleReplyAdd">回复</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {ElAvatar, ElMessage} from 'element-plus';
import {apiGet, apiPost} from "@/utils/api.ts";
//获取用户相关的数据
import {useUserStore} from '@/store/modules/user'
import {sessionStorage} from "@/utils/storage.ts";
import {useRoute, useRouter} from "vue-router";
import {formatTime} from "@/utils/time.ts";
let $router = useRouter()
const $route = useRoute();
const activeName = ref('1')
let userStore = useUserStore()
//弹出框变量
let dialogVisible = ref<boolean>(false)
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)
//总个数
let total = ref<number>(0)
//存储全部的数组
let posts = ref([])
//回复内容
let replyform = ref({
  content: '',
  postId: 0
})
//发表内容
let publishform = ref({
  title: '',
  content: ''
})
//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value
  }
  //获取表单数据
  let {data} = await apiGet('/forumPosts/findAll', parameter)
  total.value = data.count
  posts.value = data.data
}

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll()
}

//点击回复事件
const handleReply = (post) => {
  replyform.value.postId = post.postId;
  replyform.value.content = '';
  dialogVisible.value = true;
};
//点击回复添加事件
const handleReplyAdd = async () => {
  let usertoken = sessionStorage.get('USER_TOKEN');
  //如果为空，提示请先登录，否则进行下一步
  if (!usertoken) {
    ElMessage.error("请先登录");
    //跳转到登录页面
    await $router.push({path: '/login', query: {redirect: $route.path}})
    return;
  }
  let parameter = {
    content: replyform.value.content,
    postId: replyform.value.postId
  }
  await apiPost('/forumComments/add', parameter)
  dialogVisible.value = false;
  await findAll()
};
//点击发表事件
const handlePostsAdd = async () => {
  let usertoken = sessionStorage.get('USER_TOKEN');
  //如果为空，提示请先登录，否则进行下一步
  if (!usertoken) {
    ElMessage.error("请先登录");
    //跳转到登录页面
    await $router.push({path: '/login', query: {redirect: $route.path}})
    return;
  }
  let parameter = {
    title: publishform.value.title,
    content: publishform.value.content
  }
  await apiPost('/forumPosts/add', parameter)
  await findAll()
  publishform.value.title = '';
  publishform.value.content = '';
};

//删除事件
const handledelete = async (post, type) => {
  let usertoken = sessionStorage.get('USER_TOKEN');
  //如果为空，提示请先登录，否则进行下一步
  if (!usertoken) {
    ElMessage.error("请先登录");
    //跳转到登录页面
    await $router.push({path: '/login', query: {redirect: $route.path}})
    return;
  }
  if (type === 1) {
    await apiPost('/forumPosts/delete', {postId: post.postId})
  } else {
    await apiPost('/forumComments/delete', {commentId: post.title})
  }
  await findAll()
}

//组件挂载完毕
onMounted(() => {
  findAll()
})
</script>

<style scoped>
.user-info-container {
  display: flex;
  align-items: start;
  width: 100%; /* 确保整个容器的宽度是100% */
}

.user-info {
  display: flex;
  flex-direction: column;
  justify-content: start;
  width: calc(100% - 100px); /* 减去头像的宽度和一些间隔 */
  margin-left: 10px; /* 头像和用户信息的间隔 */
}

.user-details {
  display: flex;
  align-items: center;
  width: 100%; /* 确保用户详情的宽度是100% */
}

.user-content {
  margin-top: 10px;
  text-align: left;
  width: 100%; /* 帖子内容宽度为100% */
}

.replies-container {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  width: 100%; /* 确保回复容器的宽度是100% */
}

.replies-container .el-card {
  text-align: left;
  width: 100%; /* 确保每条回复的宽度是100% */
  max-width: 500px; /* 设置一个最大宽度，防止内容过多时过于宽 */
}

/* 设置头像的最大宽度，确保不会变得太大 */
.el-avatar[size="large"] {
  max-width: 80px;
  max-height: 80px;
}
</style>
